package me.lijf.xapi.security;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import me.lijf.xapi.config.MybatisConfig;
import me.lijf.xapi.dto.RestResponse;
import me.lijf.xapi.entity.User;
import me.lijf.xapi.exception.XException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Log4j2
public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private ObjectMapper mapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String token="token::"+httpServletRequest.getHeader("x-auth-token");
        String url=httpServletRequest.getRequestURI();
        if(StrUtil.isBlank(token)){
            fail(httpServletResponse, new XException(403,"请登录后使用"));
            return false;
        }
        Object value= redisTemplate.boundValueOps(token).get();
        if(value==null){
            fail(httpServletResponse, new XException(403,"会话已过期，请重新登录"));
            return false;
        }
        User user=mapper.readValue(String.valueOf(value),User.class);
        if(user.getTenant()==null){
            fail(httpServletResponse, new XException(403,"请登录业务账号使用"));
            return false;
        }
        httpServletRequest.setAttribute("user",user);
        log.info("{} >>> {}@{} 在 请求 {}",token,user.getName(),user.getTenant(), url);
        return true;
    }

    private void fail(HttpServletResponse response,XException e) throws IOException {
        response.setCharacterEncoding("UTF-8");
        //通过响应头，设置浏览器也是用UTF-8
        response.setHeader("Content-Type","text/html;charset=UTF-8");

        response.getWriter().print(mapper.writeValueAsString(RestResponse.fail(e)));
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        String token=httpServletRequest.getHeader("x-auth-token");
        log.info("{} 请求的 {} 已完成",token,httpServletRequest.getRequestURI());
    }
}
